<template>
  <!--分析报表-区域销售查询 -->
  <el-row style="height:100%">
    <page report="true">
      <div class="page-content report-con">
        <reportheader
          :option="option"
          :Caseradio='true'
          :tags='global.tags'
          :isDisabledTims='isDisabledTims'
          @upcondition="upcondition"
        ></reportheader>
        <div class="hei13"></div>
        <reportSaleCharts :title="global.title" :all_kpislist='DataV.all_kpislist' :show_kpislist="DataV.show_kpislist" :kpisKey="DataV.kpisKey"
                          :showType="showType" :x_data="xData" :title_text="titleText" :y_name="yName"
                          :y_data="yData" ref='echarts' :timeSize='timeSize'
        ></reportSaleCharts>
        <div class="hei13"></div>
        <div class="isShowTable">
          <el-button v-show="!isShowTable" type="primary" @click="isShowTable = true" size="samll" class="isShowTableBtn">
            加载报表 <i class="el-icon-arrow-down"></i>
          </el-button>
        </div>
        <reporttable v-if="isShowTable" :tableData="table.tableData" :tableHead="table.tableHead" :showType="showType" :comp_name="DataV.comp_name"
          ref='table' :title="global.title" :isShowExport = "timeSize.isShow"></reporttable>
        <Table v-if="false" ref="Table" :data="tdata" :column="tcolumn" :show_kpislist="DataV.show_kpislist"></Table>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .page-content {
    &.report-con {
      padding: 0 0;
    }

    padding: 15px;

    .fr {
      float: right;
    }

    .el-table {
      margin-bottom: 10px;
    }

    .paging {
      margin: 15px;
      height: 28px;
    }

    .hei13 {
      height: 15px;
      width: 100%;
    }
  }
  .isShowTable{
    width: 100%;
    display: block;
    text-align: center;
    margin:20px 0;
    .isShowTableBtn{
      margin: 0 auto;
    }
  }
</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import reportheader from "@/components/analyzeReport/reportpublic/reportheader";
  import reportSaleCharts from "@/components/analyzeReport/reportpublic/reportSaleCharts";
  import reporttable from "@/components/analyzeReport/reportpublic/reporttable";
  import reportGlobal from "@/components/global/reportGlobal";//公共配置
  import Table from "@/components/common/table";//表格组件
  let unit = reportGlobal.unit;
  let kpiColor = reportGlobal.colorList;
  let kpiName = reportGlobal.name;
  let showTableMaxItemList = reportGlobal.showTableMaxItemList;
  export default {
    data: function () {
      return {
        option: {
          shortcuts: 'dayShortcuts',
          isAreaShow: true,                 //是否显示区域，如显示需传title 默认不显示
          caseTitle: "",
          areaTitle: "",
        },
        table: {
          tableData: [],
          tableHead: [],
        },//表格数据
        showType: 'time',  //展示类型(time:分时,distr:分布)
        DataV: {
          all_kpislist:[],//全部的指标数组
          show_kpislist:[],//当前显示的指标数组
          kpisKey:[],//当前显示的指标（key值）

          kpislist:[],//指标交集
          nowKpisList:[],//当前选中的指标list
          nowKpisKey:[],//当前选中的指标key值数组
        },      //head条件接收
        xData: [],
        yData: [],
        yName: [],
        titleText: "",
        commonData: null,
        timeSize: {
          list: [],
          check: ''
        },

        echartKpis: [],//echart指标
        global: {},//公共参数
        code: this.$route.query.code,        //通过菜单栏点击传过来的code判断使用的公共参数
        isShowTable:false,//是否显示表格
        tdata:[],
        isDisabledTims:false,
        tcolumn:[],
        xxloading:true,   //提示信息遮罩层
        showTable:false,
      };
    },
    components: {
      page,
      reportheader,
      reportSaleCharts,
      reporttable,
      Table,
    },
    inject: ["reload"],
    created() {
      //根据code来获取公共参数
      for (let i in reportGlobal.queryList) {
        if (this.code == reportGlobal.queryList[i].code) {
          this.global = reportGlobal.queryList[i]
        }
      }
      this.option.caseTitle = this.global.caseTitle
      this.option.areaTitle = this.global.areaTitle
    },
    mounted() {
      //合计分项分时分布
      this.$Bus.$on('upsum_part', (sum_or_part,showType,ishavaData = true) => {
        if (!ishavaData) {
          this.removedata();
          this.$Bus.$emit("Loading", false);
          return
        }
        if(!this.commonData) return

        //判断如果是分布时，则不现实时间粒度
        this.isDisabledTims = showType == 'distr' ? false : true

        if (Object.keys(this.DataV).length > 0) {
          this.DataV.sum_or_part = sum_or_part;
          this.showType = showType;
          this.checkInterval();
        } else {
          console.log("暂无数据");
          this.removedata();
          this.$Bus.$emit("Loading", false);
        }
      });

      this.$Bus.$on('TimegranuChange', val => {
        this.timeSize.check = val;
        if(Object.keys(this.DataV).length==0){
          this.$message.warning('参数有误，请检查选择条件！')
          this.$Bus.$emit('Loading',false)
          return
        }
        this.isShowExport()
        this.checkInterval();
      });
      //表格指标点击
      this.$Bus.$on('echartsKpiCheck', (val,isFirst) => {
        this.DataV.nowKpisKey = val;
        //如果不是第一次触发时
        if (!isFirst) {
          if(!this.commonData) return
          this.$Bus.$emit('Loading', true);
          this.Upecharts();
          this.Uptable();
        }
      })
      //保存更多指标
      this.$Bus.$on('saveMore', (kpiCheckType,Kpisvalue) => {
        this.DataV.nowKpisKey = kpiCheckType;
        this.DataV.kpisKey = Kpisvalue.map(x=>x.key)
        this.DataV.show_kpislist = Kpisvalue
        this.$nextTick(()=>{
          this.Updata(true)
        })
      })
      //切换企业时清空数据
      this.$Bus.$on('Remove', () => {
        this.removedata(true);
      });
    },
    beforeDestroy() {
      this.$Bus.$off('TimegranuChange')
      this.$Bus.$off('upsum_part')
      this.$Bus.$off('echartsKpiCheck')
      this.$Bus.$off('Remove')
      this.$Bus.$off('saveMore')
    },
    watch: {
      commonData:{
        handler(val){
          // console.log(val);
          if(val && Object.keys(val).length) {
            this.Upecharts();
            this.Uptable();
          }
        },
        deep:true
      },
      //当route变化的时候，主要是报表之前传参
      $route(){
        this.reload()
      },
    },
    methods: {
      upcondition(data,showType,isSendTimeSize,isKeepKPI){
        Object.assign(this.DataV, data);
        this.showType = showType
        if(isKeepKPI){
          this.getKpis(data.area);//案场
          return
        }else{
          this.checkInterval();
        }
      },
      //获取指标接口
      getKpis(id,org_type=3) {
        this.$Bus.$emit('Loading', true);
        let getKPIList = ()=>{
          let p = new Promise((res,rej)=>{
            let url='/sys/report_assist_new/get_indicator_list'
            let params = {
              org_id_list :id,
              org_type :org_type,
            }
            this.$api.post(url,params)
            .then(data => {
              if(data == '10001'){
                this.$message.error('无权操作该数据')
                rej()
              }
              if (data) {
                res(data.data)
              } else {
                rej()
              }
            })
            .catch(err => {
              rej(err)
              console.log(err, '企业下无指标');
              this.removedata();
              this.$Bus.$emit('Loading', false);
            })
          })
          return p
        }
        //获取当前显示的kpi
        let getShowKPI = ()=>{
          let p = new Promise((res,rej)=>{
            let url = '/sys/report_assist_new/set_web_custom_storage?w_key='+ this.code
            this.$api.get(url)
            .then(data=>{
              res(data.data)
            })
            .catch(err=>{
              rej(err)
            })
          })
          return p
        }
        Promise.all([getKPIList(),getShowKPI()])
        .then(data=>{
          let kpiList = data[0]
          let showKPi = data[1]
          this.DataV.all_kpislist = kpiList.filter(x => {
            return this.global.indicator_keys.includes(x.key)
          })

          //根据id对指标进行排序
          this.DataV.all_kpislist.sort((x,y)=>{
            if(x.id < y.id){
              return -1
            }else{
              return 1
            }
          });
          //判断是否get到显示的指标
          if(showKPi){
            showKPi = JSON.parse(showKPi)
            this.DataV.show_kpislist = [];
            for(let i in showKPi){
              for(let j in this.DataV.all_kpislist){
                if(this.DataV.all_kpislist[j].key == i && showKPi[i]){
                  this.DataV.show_kpislist.push(this.DataV.all_kpislist[j])
                }
              }
            }
          }else{
            this.DataV.show_kpislist = this.DataV.all_kpislist.filter(x => {
              return this.global.showKPI.includes(x.key)
            })
          }
          //判断显示的kpi值有没有
          if(this.DataV.show_kpislist.length == 0){
            this.DataV.show_kpislist = this.DataV.all_kpislist.length <= 8 ? this.DataV.all_kpislist.map(x=>x) :
              this.DataV.all_kpislist.filter((x,i)=>{
                return i <= 7
              })
          }
          this.DataV.kpisKey = this.DataV.show_kpislist.map(x=>x.key)
          this.DataV.nowKpisKey = Array.of(this.DataV.show_kpislist[0].key)
           console.log(this.DataV,'this.DataV');

          this.$nextTick(()=>{
            this.checkInterval()
          })
        })
        .catch(err=>{
          console.log(err);
        })
      },
      //颗粒度是否合法
      checkInterval(){
        let url = '/sys/report_assist_new/check_interval?interval=' + this.timeSize.check +
          "&start_day=" + this.DataV.start_day + "&end_day=" + this.DataV.end_day + "&start_hm=" + this.DataV.start_hm + "&end_hm=" + this.DataV.end_hm
        this.$api.post(url)
        .then(res=>{
          if(res == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(res.data){
            this.Updata(true)
          }else{
            this.Updata(false)
          }
        })
      },

      Updata(isSendTimeSize = true,org_type=3) {
        this.isShowTable = false
        if(!this.DataV.area.length)
        {
          this.$message.warning('该企业下无'+this.option.areaTitle+'！')
          this.$Bus.$emit("Loading", false);
          return
        }
        if (!Object.keys(this.DataV).length > 0) {
          this.removedata();
          this.$Bus.$emit("Loading", false);
          return
        }
        this.$Bus.$emit("Loading", true);
        let url = '';
        if (this.showType == 'time') {
          url = "/sys/report_new/time_division_sum?"
        } else if (this.showType == 'distr') {
          url = "/sys/report_new/distribution_sum?sort_type=desc&sort_key=" + this.DataV.kpisKey[0] +'&';
        }
        url += "tags=" + this.global.tags + "&indicator_keys=" + this.DataV.kpisKey + '&group_type=area';

        if (this.timeSize.check && this.showType != 'distr' && isSendTimeSize) url += "&interval=" + this.timeSize.check;

        url += "&start_day=" + this.DataV.start_day + "&end_day=" + this.DataV.end_day + "&start_hm=" + this.DataV.start_hm + "&end_hm=" + this.DataV.end_hm;
        let params ={
          org_id_list :this.DataV.area,
          org_type:org_type
        }
        this.$api.post(url,params)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          this.timeSize.list = data.data.interval_list || [];
          if(this.showType == 'time'){
            if(this.timeSize.check && isSendTimeSize){
                this.timeSize.check = this.timeSize.check
            }else{
              this.timeSize.check = data.data.cur_interval.tag;
            }
          }
          if(data && data.data){
            let item_list_length = data.data.item_list ? data.data.item_list.length : 0//获取item_list的长度
            //判断是否直接显示报表，如果item_list_length > 20 时，则不显示报表
            this.isShowTable = item_list_length > showTableMaxItemList ? false : true


            if(this.showType == 'time'){
              let isDay = this.timeSize.list.filter(x=>{
                return x.type != 'DAY'
              })
              this.isDisabledTims = isDay.length == 0 ? true : false
             
            }
            this.isShowExport()
            if (data.data.item_list && data.data.item_list.length > 0) {
              this.commonData = data.data;     //改变数据
            }else{
              this.removedata();
            }
          }else{
            this.removedata();
          }
          this.$Bus.$emit("Loading", false);
        })
        .catch(err => {
           console.log(err);
          this.removedata();
          this.$Bus.$emit("Loading", false);
        });
      },

      //分时柱状图数据改变
      Upecharts() {
        if (!Object.keys(this.commonData).length) {
          this.$message.error('没有数据！')
          this.$Bus.$emit('Loading', false);
          return
        }
        let data = this.DataV.sum_or_part == 'sum' ? [this.commonData.sum_list] : this.partArr(this.commonData.item_list);
        let showKpislist = this.DataV.nowKpisKey;
        let tempObj = [];
        //数据转换成echarts需要数据
        for (let i = 0; i < data.length; i++) {
          let echartsval = {};
          echartsval.area_name = [];  //分布区域/案场名 x轴
          echartsval.time_tag = []; //分时x轴显示
          for(let kpi in showKpislist){
            echartsval[showKpislist[kpi]] = [];
            for (let j = 0; j < data[i].length; j++) {
              echartsval[showKpislist[kpi]].push(data[i][j][showKpislist[kpi]]);
              echartsval.area_name.push(data[i][j].area_name);
              echartsval.time_tag.push(data[i][j].time_tag);
            }
          }
          tempObj.push(echartsval);
        }

        let x_data = [];
        let y_data = {};
        let y_name = {};
        for(let kpi in showKpislist){
          y_data[showKpislist[kpi]] = [];
          y_name[showKpislist[kpi]] = [];
        }
        let t_text = "";
        //根据指标顺序传入echarts数据
        if (this.showType == 'time') {
          if (this.DataV.sum_or_part == 'sum') {
            for (let i = 0; i < showKpislist.length; i++) {
              y_name[showKpislist[i]].push("全部-"+ kpiName[showKpislist[i]]);
              y_data[showKpislist[i]].push(tempObj[0][showKpislist[i]]);
            }
          } else {
            for (let i = 0; i < showKpislist.length; i++) {
              for (let j = 0; j < tempObj.length; j++) {
                y_name[showKpislist[i]].push(tempObj[j].area_name[0]+"-"+ kpiName[showKpislist[i]]);
                y_data[showKpislist[i]].push(tempObj[j][showKpislist[i]]);
              }
            }
          };
          // console.log(y_data);
          // let arr=[];
          // for(let i=0;i<tempObj.length;i++){
          //   arr=[...arr,...tempObj[i].time_tag];
          // }
          let xarr=[];
          for(let i in tempObj) {
             xarr=[...xarr,...tempObj[i].time_tag];
          }
          x_data =new Set(xarr);    //分时x轴
          //分时时间转换
        } else if (this.showType == 'distr') {
          for (let i = 0; i < showKpislist.length; i++) {
            let mode = [];
            if(this.DataV.sum_or_part=='sum')
            {
              for (let j = 0; j < tempObj.length; j++) {
                mode.push(tempObj[j][showKpislist[i]][0]);
              }
            }
            else{
              for (let j = 0; j < this.commonData.item_list.length; j++) {
                mode.push(this.commonData.item_list[j][showKpislist[i]]);
                x_data.push(this.commonData.item_list[j].area_name);
              }
            }
            y_data[showKpislist[i]].push(mode);
            y_name[showKpislist[i]].push(kpiName[showKpislist[i]]);
          }

          //分布x轴
          if(this.DataV.sum_or_part=='sum')
          {
            for (let i = 0; i < tempObj.length; i++)
              x_data.push(tempObj[i].area_name[0]);
          }
          //分布时间转换
          t_text = this.getWeekShow();       //echarts 多少周~多少周(title)
        }
        //得到新数据改变echarts数据
        this.xData = [...new Set(x_data)];
        this.titleText = t_text;
        this.yName = y_name;
        this.yData = y_data;
        this.$nextTick(() => {
          this.$refs.echarts.UpData(true);
          this.$Bus.$emit("Loading", false);
        })
        this.$Bus.$emit("Loading", false);
      },
      aUptable(){
        this.showTable = false
        let column = [];//表头
        let center_arr = [];//中间数据内容
        let tableData = [];
        let showKpislist = [...this.DataV.nowKpisKey];//显示的指标数组
        let showType = this.showType;//当前显示的是分时，分布报表；'tiem':分时，'distr':分布
        // console.log(showKpislist,'showKpislist');
        let sum_list = this.commonData.sum_list.length ? this.commonData.sum_list : [];//合计列表
        let item_list = this.commonData.item_list.length ? this.commonData.item_list : [];//item列表
        let avg_list = this.commonData.avg_list.length ? this.commonData.avg_list : [];//平均值列表

        //当为分时表报时
        if(showType === 'time'){
          //获取表头菜单
          column = [
            {
              name:'案场名称',
              key: 'case_info_name',
              width: 100,
              align: 'center',
              frozen: 'left',
            },
            {
              name:'案场编号',
              key: 'case_code',
              width: 100,
              align: 'center',
              frozen: 'left',
            },
            {
              name:'区域名称',
              key: 'area_name',
              width: 100,
              align: 'center',
              frozen: 'left',
            },
            {
              name:'指标',
              key: 'kpi_name',
              width: 100,
              align: 'center',
              frozen: 'left',
            },
          ]

          for(let i in sum_list){
            let obj = {
              name:'',
              key: '',
              width: 100,
              align: 'center',
              frozen: '',
            }
            obj.name = sum_list[i].time_tag
            obj.key = sum_list[i].time_tag
            center_arr.push(obj)
            column.push(obj)
          }
          column.push(
            {
              name:'平均',
              key: 'avg',
              width: 100,
              align: 'center',
              frozen: 'right',
            },
            {
              name:'小计',
              key: 'subtotal',
              width: 100,
              align: 'center',
              frozen: 'right',
            }
          )
          // console.log(column,'column');
          // console.log(center_arr,'center_arr');
          //获取data数据
          let data = []
          let showKpislistLength = showKpislist.length;//指标个数
          let idArr = []

          //先把数据中不同的案场id拿到放入一个数组中
          for(let i in item_list){
            if(!idArr.includes(item_list[i].case_info_id)){
              idArr.push(item_list[i].case_info_id)
            }
          }

          //再遍历案场id数组，根据id不同创建对象
          for(let i in idArr){
            let caseObj = {}
            for(let j in item_list){
              if(idArr[i] == item_list[j].case_info_id){
                caseObj.case_info_id = item_list[j].case_info_id
                caseObj.case_info_name = item_list[j].case_info_name
                caseObj.case_code = item_list[j].case_code
                caseObj.area_arr = []
                for(let k in item_list){
                  let obj = {}
                  let area_id_arr = caseObj.area_arr.map(x=>x.area_id)
                  let indexOf = area_id_arr.indexOf(item_list[k].area_id)
                  if(indexOf == -1){
                    obj.area_id = item_list[k].area_id
                    obj.area_name = item_list[k].area_name
                    obj.rowspan = showKpislistLength
                    for(let l in showKpislist){
                      obj[showKpislist[l]] = {}
                      for(let item in center_arr){
                        obj[showKpislist[l]][center_arr[item].key] = item_list[k][showKpislist[l]] ? item_list[k][showKpislist[l]] : '--'
                      }
                    }
                    caseObj.area_arr.push(obj)
                  }else{
                    for(let l in showKpislist){
                      caseObj.area_arr[indexOf][showKpislist[l]][item_list[k].time_tag] = item_list[k][showKpislist[l]] ? item_list[k][showKpislist[l]] : '--'
                    }
                  }
                }
              }
            }
            caseObj.rowspan = caseObj.area_arr.length * showKpislistLength
            //把做好的数据push进data中
            data.push(caseObj)
          }

          // console.log(data,'data');
          let tableData = [];//最终传参的tableData参数
          //遍历data数据合成table组件想要的数据格式
          for(let i in data){
            let caseObj = {}
            caseObj.case_info_name = {}
            caseObj.case_code = {}
            caseObj.area_name = {}
            caseObj.kpi_name = {}

            caseObj.case_info_name.value = data[i].case_info_name
            caseObj.case_info_name.rowspan = data[i].rowspan
            caseObj.case_code.value = data[i].case_code
            caseObj.case_code.rowspan = data[i].rowspan

            for(let j in data[i].area_arr){
              if(j == 0){
                caseObj.area_name.value = data[i].area_arr[j].area_name
                caseObj.area_name.rowspan = data[i].area_arr[j].rowspan
                this.kpisListObj(caseObj,showKpislist,data[i].area_arr[j],tableData)
              }else{
                let areaObj = {}
                areaObj.area_name = {}
                areaObj.area_name.value = data[i].area_arr[j].area_name
                areaObj.area_name.rowspan = data[i].area_arr[j].rowspan
                this.kpisListObj(areaObj,showKpislist,data[i].area_arr[j],tableData)
              }
            }
          }

          let sumObj = {
            case_info_name:{
              value:'合计',
              rowspan:showKpislist.length,
            },
            case_code:{
              value:'合计',
              rowspan:showKpislist.length,
            },
            area_name:{
              value:'合计',
              rowspan:showKpislist.length,
            },
            kpi_name:{},
          }
          let avgObj = {
            case_info_name:{
              value:'平均',
              rowspan:showKpislist.length,
            },
            case_code:{
              value:'平均',
              rowspan:showKpislist.length,
            },
            area_name:{
              value:'平均',
              rowspan:showKpislist.length,
            },
            kpi_name:{},
          }
          let sum_data = this.createData(showKpislist,sum_list)//生成合计数据
          let avg_data = this.createData(showKpislist,avg_list)//生成平均数据
          this.kpisListObj(sumObj,showKpislist,sum_data,tableData)
          this.kpisListObj(avgObj,showKpislist,avg_data,tableData)

          this.showTable = true
          this.$nextTick(()=>{
            this.$refs.Table.getTableData(tableData,column,this.showType)
          })

        }else{
          //添加进出客流占比
          if(showKpislist.includes('enters')){
            let index = showKpislist.indexOf('enters')
            showKpislist.splice(index,1,'enters','entersProportion')
            kpiName.entersProportion = '进入客流占比'
          }
          if(showKpislist.includes('exits')){
            let index = showKpislist.indexOf('exits')
            showKpislist.splice(index,1,'exits','exitsProportion')
            kpiName.entersProportion = '离开客流占比'
          }
          console.log(showKpislist,'showKpislist');
          console.log(item_list,'item_list');
          console.log(sum_list,'sum_list');
          if(showKpislist.includes('enters') || showKpislist.includes('exits')){
            item_list = this.pushProportion(item_list,sum_list,showKpislist)
          }
          column = [
            {
              name:'案场名称',
              key: 'case_info_name',
              width: 100,
              align: 'center',
            },
            {
              name:'案场编号',
              key: 'case_code',
              width: 100,
              align: 'center',
            },
            {
              name:'区域名称',
              key: 'area_name',
              width: 100,
              align: 'center',
            },
          ];

          for(let i in showKpislist){
            let kpi = showKpislist[i]
            //判断指标是否为进出人数时，添加一列
            if(showKpislist[i] == 'entersProportion'){
              let obj = {
                name:'进入客流占比',
                key: kpi,
                width: 100,
                align: 'center',
              }
              column.push(obj);
            }else if(showKpislist[i] == 'exitsProportion'){
              let obj = {
                name:'离开客流占比',
                key: kpi,
                width: 100,
                align: 'center',
              }
              column.push(obj);
            }else{
              let obj = {
                name:kpiName[kpi],
                key: kpi,
                width: 100,
                align: 'center',
              }
              column.push(obj)
            }
          }

          //获取data数据
          let data = []
          let showKpislistLength = showKpislist.length;//指标个数
          let idArr = []

          //先把数据中不同的案场id拿到放入一个数组中
          for(let i in item_list){
            if(!idArr.includes(item_list[i].case_info_id)){
              idArr.push(item_list[i].case_info_id)
            }
          }
          console.log(idArr,'idArr');
          //再遍历案场id数组，根据id不同创建对象
          for(let i in idArr){
            let caseObj = {}
            for(let j in item_list){
              if(idArr[i] == item_list[j].case_info_id){
                caseObj.case_info_id = item_list[j].case_info_id
                caseObj.case_info_name = item_list[j].case_info_name
                caseObj.case_code = item_list[j].case_code
                caseObj.area_arr = []
                for(let k in item_list){
                  let obj = {}
                  let area_id_arr = caseObj.area_arr.map(x=>x.area_id)
                  let indexOf = area_id_arr.indexOf(item_list[k].area_id)
                  if(indexOf == -1){
                    obj.area_id = item_list[k].area_id
                    obj.area_name = item_list[k].area_name
                    obj.rowspan = 1
                    caseObj.area_arr.push(obj)
                  }
                }
              }
            }
            caseObj.rowspan = caseObj.area_arr.length
            //把做好的数据push进data中
            data.push(caseObj)
          }
          console.log(data,'data');

          for (let i in data) {
            let caseObj = {}
            caseObj.case_info_name = {}
            caseObj.case_code = {}
            caseObj.area_name = {}

            caseObj.case_info_name.value = data[i].case_info_name
            caseObj.case_info_name.rowspan = data[i].rowspan
            caseObj.case_code.value = data[i].case_code
            caseObj.case_code.rowspan = data[i].rowspan
            for (let j in data[i].area_arr) {
              if (j == 0) {
                caseObj.area_name.value = data[i].area_arr[j].area_name
                caseObj.area_name.rowspan = data[i].area_arr[j].rowspan
                this.disKpiListObj(caseObj, showKpislist, data[i].area_arr[j].area_id, tableData, item_list)
              } else {
                let areaObj = {}
                areaObj.area_name = {}
                areaObj.area_name.value = data[i].area_arr[j].area_name
                areaObj.area_name.rowspan = data[i].area_arr[j].rowspan
                this.disKpiListObj(areaObj, showKpislist, data[i].area_arr[j].area_id, tableData, item_list)
              }
            }
          }

          console.log(tableData,'tableData');
          this.showTable = true
          this.$nextTick(()=>{
            this.$refs.Table.getTableData(tableData,column,this.showType)
          })
        }


        this.tdata = tableData
        this.tcolumn = column
      },
      createRowspan(i){
        let rowspan = 0

      },
      //生成数据
      createData(showKpislist,list){
        let data = {}
        for(let i in showKpislist){
          let value = {};//
          let kpi = showKpislist[i]
          for(let i in list){
            value[list[i].time_tag] = list[i][kpi] ? list[i][kpi] : '--'
          }
          data[kpi] = value
        }
        return data
      },
      //分时数据遍历指标，
      kpisListObj(obj,showKpislist,area_arr,tableData){
        for(let k in showKpislist){
          let kpi = showKpislist[k]
          let kpiValueObj = area_arr[kpi]
          let isPercentage = unit[kpi] === '%' ? true : false
          //判断是否是第一个指标，为了实现合并列的效果，只有第一个指标的数据是全的，其他的都只有value数据
          if(k == 0){
            obj.kpi_name = {}
            obj.kpi_name.value = kpiName[kpi]+'('+ unit[kpi] + ')'
            obj = this.kpiValueObj(obj,kpiValueObj,isPercentage)
            tableData.push(obj)
          }else{
            let kpiObj = {}
            kpiObj.kpi_name = {}
            kpiObj.kpi_name.value = kpiName[kpi]+'('+ unit[kpi] + ')'
            kpiObj = this.kpiValueObj(kpiObj,kpiValueObj,isPercentage)
            tableData.push(kpiObj)
          }
        }
      },
      //分布数据遍历指标
      disKpiListObj(obj,showKpislist,area_id,tableData,item_list){
        for(let i in showKpislist){
          let kpi = showKpislist[i]
          obj[kpi] = {}
          for(let j in item_list){
            if(item_list[j].area_id == area_id){
              obj[kpi].value = item_list[j][kpi] ? item_list[j][kpi] : '--'
              obj[kpi].isCenterValue = true;//用来判断哪些td是数据，用来控制
            }
          }
        }
        tableData.push(obj)
      },
      //分时数据遍历以时间key的数据，同时给每一行数据加上最大最小值和平均，小计
      kpiValueObj(obj,kpiValueObj,isPercentage){
        // console.log(kpiValueObj);
        let data_arr = Object.values(kpiValueObj);
        //排除掉不是数字的元素
        let new_data_arr = data_arr.filter(x=> {
          return !Number.isNaN(parseFloat(x))
        })
        // console.log(data_arr,'data_arr');
        if(new_data_arr.length){
          let max = Math.max(...new_data_arr)
          let min = Math.min(...new_data_arr)
          let isPushMax = false
          let isPushMin = false
          for(let i in kpiValueObj){
            obj[i]={}
            obj[i].value = kpiValueObj[i]
            obj[i].isCenterValue = true;//用来判断哪些td是数据，用来控制
            if(kpiValueObj[i] === max && !isPushMax){
              obj[i].max = true
              isPushMax = true
            }else if(kpiValueObj[i] === min && !isPushMin){
              obj[i].min = true
              isPushMin = true
            }
          }
          let sum = Number(new_data_arr.reduce((x,y)=>{
            return x+y
          }))
          let avg = ((sum / new_data_arr.length).toFixed(2) * 100) / 100
          obj.avg = {}
          obj.subtotal = {}
          obj.avg.value = avg
          obj.subtotal.value = isPercentage ? '--' : sum
        }else{
          for(let i in kpiValueObj){
            obj[i]={}
            obj[i].value = kpiValueObj[i]
            obj[i].isCenterValue = true
          }
          obj.avg = {}
          obj.subtotal = {}
          obj.avg.value = '--'
          obj.subtotal.value = '--'
        }

        return obj
      },

      Uptable() {
        this.aUptable()
        let data;
        let t_head = []; //组装表头数据
        let t_data = []; //组装表格数据
        let showKpislist = this.DataV.nowKpisKey;
        // console.log(this.commonData,'this.commonData');
        if (this.showType == 'time') {
          // console.log(this.commonData,'427');
          data = this.commonData.sum_list;

          if (Object.keys(data).length > 0) {
            let kpisval = []; //提取指标
            let timeval = []; //提取时间
            const N = data.length; //数据条数
            //提取时间
            for (let i = 0; i < N; i++) {
              //  console.log(data[i].end_time)
              timeval.push(data[i].time_tag);
            }
            //临时组装表头数据
            for (let i = 0; i < N; i++) {
              let model = {};
              model.prop = model.label = timeval[i];
              t_head.push(model);
            }
            let itemArr = this.partArr(this.commonData.item_list)

            //临时组装表格数据 一组
            let tempdata;
            for (let i = 0; i < itemArr.length; i++) {
              data = itemArr[i];
              kpisval = this.extractKpis(data, showKpislist);
              tempdata = this.getTableData(data, showKpislist, kpisval, timeval);
              t_data = [...t_data, ...tempdata];
            }

            //临时组装表格数据 合计
            data = this.commonData.sum_list;
            kpisval = this.extractKpis(data, showKpislist);
            tempdata = this.getTableData(data, showKpislist, kpisval, timeval);
            t_data = [...t_data, ...tempdata];
            //临时组装表格数据 平均
            data = this.commonData.avg_list;
            kpisval = this.extractKpis(data, showKpislist);
            tempdata = this.getTableData(data, showKpislist, kpisval, timeval);
            t_data = [...t_data, ...tempdata];
          } else {
            this.table.tableData = [];
            this.table.tableHead = [];
            return;
          }
        } else {                               //分布
          //分布表头数据
          for (let i = 0; i < showKpislist.length; i++) {
            let model = {};
            model.prop = showKpislist[i];
            model.label = this.getkpiName(showKpislist[i]);

            t_head.push(model);
            //判断指标是否为进出人数时，添加一列
            if(showKpislist[i] == 'enters'){
              let newModel = {}
              newModel.prop = 'entersProportion'
              newModel.label = '进入客流占比'
              t_head.push(newModel);
            }else if(showKpislist[i] == 'exits'){
              let newModel = {}
              newModel.prop = 'exitsProportion'
              newModel.label = '离开客流占比'
              t_head.push(newModel);
            }
          }
          let item_list_tempObj,sum_list_tempObj;
          let item_list_data,sum_list_data;
          //分布表格数据
          item_list_data = this.commonData.item_list;
          item_list_tempObj = this.getTableDisrt(item_list_data, showKpislist);
          //合计
          sum_list_data=this.commonData.sum_list;
          sum_list_tempObj=this.getTableDisrt(sum_list_data,showKpislist);

          if(showKpislist.includes('enters') || showKpislist.includes('exits')){
            item_list_tempObj = this.pushProportion(item_list_tempObj,sum_list_tempObj,showKpislist)
          }
          t_data=[...item_list_tempObj,...sum_list_tempObj];
        }
        this.table.tableData = [];
        this.table.tableHead = [];
        this.table.tableData = t_data;
        this.table.tableHead = t_head;
      },
      //table分布表格数据(合计)
      getTableDisrt(data, showKpislist) {
        let t_data = [];
        for (let i = 0; i < data.length; i++) {
          let model = {};
          model.case_id=data[i].case_info_id;
          model.area_id=data[i].area_id;
          model.case = data[i].case_info_name == 'sum' ? '合计' : data[i].case_info_name;
          model.area = data[i].area_name != null ? data[i].area_name : '合计';
          model.case_code= data[i].case_info_name == 'sum' ? '合计' : data[i].case_code;
          for (let j = 0; j < showKpislist.length; j++) {
            if(showKpislist[j] == 'enters_rate' || showKpislist[j] == 'churn_rate'){
              model[showKpislist[j]] = data[i][showKpislist[j]] == null ? '--':data[i][showKpislist[j]]+unit[showKpislist[j]] ?
                (data[i][showKpislist[j]].toFixed(2) * 100) / 100 : data[i][showKpislist[j]]+ unit[showKpislist[j]];
            }else{
              model[showKpislist[j]] = data[i][showKpislist[j]] == null ? '--':data[i][showKpislist[j]]+unit[showKpislist[j]];
            }
          }
          let isnull=true;
          for(let y=0;y<showKpislist.length;y++) {
            if(model[showKpislist[y]] != '--') {
              isnull=false;
              break;
            }
          }
          model.isnull=isnull;
          t_data.push(model);
        }
        return t_data;
      },
      //分布报表指标包含进出客流时添加客流占比数据
      pushProportion(item_list_tempObj,sum_list_tempObj,showKpislist){
        let sum_enters = parseFloat(sum_list_tempObj[0].enters)
        let sum_exits = parseFloat(sum_list_tempObj[0].exits)
        if(showKpislist.includes('enters')){
          for(let i in item_list_tempObj){
            item_list_tempObj[i].entersProportion =
              (item_list_tempObj[i].enters != '--' && item_list_tempObj[i].enters != null) && sum_enters
              ? ((parseFloat(item_list_tempObj[i].enters) / sum_enters) * 100).toFixed(2) + '%' : '--'
          }
        }
        if(showKpislist.includes('exits')){
          for(let i in item_list_tempObj){
            item_list_tempObj[i].exitsProportion =
              (item_list_tempObj[i].exits != '--' && item_list_tempObj[i].exits != null) && sum_exits
              ? ((parseFloat(item_list_tempObj[i].exits) / sum_enters) * 100).toFixed(2) + '%' : '--'
          }
        }
        return item_list_tempObj
      },
      //table提取指标对应的数据 //
      extractKpis(data, showKpislist) {
        let kpisval = [];
        for (let item in showKpislist) {
          let model = [];
          for (let i = 0; i < data.length; i++) {
            model.push(data[i][showKpislist[item]]);
          }
          kpisval.push(model);
        }
        return kpisval
      },
      //table 分开提取表格数据 （如平均、合计、案场等）;
      getTableData(data, showKpislist, kpisval, timeval) {
        let t_data = [];
        if(data.length){
          for (let i = 0; i < showKpislist.length && data.length > 0; i++) {
            let model = {};
            model.case_id=data[0].case_info_id;
            model.area_id=data[0].area_id;
            model.case = data[0].case_info_name == 'avg' ? '平均值' : (data[0].case_info_name == 'sum' ? '合计' : data[0].case_info_name);
            model.area = data[0].area_name != null ? data[0].area_name : (data[0].case_info_name == 'avg' ? '平均值' : (data[0].case_info_name == 'sum' ? '合计' : data[0].area_name));
            model.kpi = this.getkpiName(showKpislist[i])+'('+unit[showKpislist[i]]+')';
            model.aver =unit[showKpislist[i]] == '%'? (data[0].case_info_name == 'sum'?'--': this.getSumAver(kpisval[i], true)+'%'): this.getSumAver(kpisval[i], true);
            model.sum = unit[showKpislist[i]] == '%' ? '--' : this.getSumAver(kpisval[i]);
            model.case_code=data[0].case_info_name == 'avg' ? '平均值' : (data[0].case_info_name == 'sum' ? '合计' : data[0].case_code);
            for (let j = 0,s=0; j < timeval.length; j++) {
              let key = timeval[j];
              if(data[0].case_info_name=='sum' && unit[showKpislist[i]]=='%'){
                model[key] ='--';
              }
              else if(s<data.length && timeval[j]==data[s].time_tag )
              {
                model[key] =kpisval[i][s]==null?'--':(unit[showKpislist[i]]=='%'?kpisval[i][s]+'%':kpisval[i][s]);
                s++;
              }
              else{
                model[key] ='--';
              }

            }
           
            var arr=kpisval[i].filter(item=>item);    //去掉数组中的null,undefined
            if(arr.length){
              model.isnull=false;
              model.max = arr.reduce(function(a , b){
                          return b > a ? b : a;
                        });
              model.min = arr.reduce(function(a , b){
                          return b < a ? b : a;
                        });
            }
            else{
              model.isnull=true;
              model.max =null;
              model.min =null;
              model.aver='--';
              model.sum='--';
            }
            t_data.push(model);
          }
        }
        return t_data;
      },
      //得到时间格式
      getTimeFormay(formay) {
        let str = "MM月DD日 HH:mm"; //时间戳格式
        if (formay.indexOf("DAY") != -1) {
          str = "MM月DD日";
        } else if (formay.indexOf("WEEK") != -1) {
          str = "YYYY-MM-DD";
        }
        return str;
      },
      //得到指标中文名
      getkpiName(kpiname) {
        return kpiName[kpiname];
      },
      //得到指标中文名
      getkpiUnit(kpiname) {
        return unit[kpiname];
      },
      //求和或平均值    求平均值isaver=true
      getSumAver(arr, isaver) {
        let sum = 0;
        for (let i = 0; i < arr.length; i++) {
          sum += arr[i];
        }
        if (isaver) {
          return ((sum / arr.length).toFixed(2) * 100) / 100;
        } else {
          return sum;
        }
      },
      //获取该行数据中的小计或平均值
      getAvgOrSum(list,kpi,isAvg){
        let sum = 0;
        for (let i in list) {
          sum += list[i][kpi];
        }
        if (isAvg) {
          return ((sum / list.length).toFixed(2) * 100) / 100;
        } else {
          return sum;
        }
      },
      //清除数据
      removedata(iscomp=false) {
        this.$refs.echarts.UpData(false);
        this.table.tableData = [];
        this.table.tableHead = [];
        this.commonData = null;
        if(iscomp) this.DataV = {};
      },
      //echarts 周数显示
      getWeekShow() {
        let strtime = this.DataV.start_day;
        let endtime = this.DataV.end_day;
        let tempdate = moment(strtime).format("YYYY-MM-DD");
        let a_week = moment(tempdate).get('week');
        let end_tempdate = moment(endtime).format("YYYY-MM-DD");
        let end_a_week = moment(end_tempdate).get('week');
        let str = '';
        if (tempdate == end_tempdate) {
          str = end_tempdate + ' 周' + moment(endtime).format("d");
          return str;
        }
        if (a_week == end_a_week) {

          str = tempdate + ' ~ ' + end_tempdate + ' 第' + end_a_week + '周';

        } else {
          str = tempdate + ' 第' + a_week + '周 ~ ' + end_tempdate + ' 第' + end_a_week + '周';
        }
        return str;

      },

      //数组分项
      partArr(arr) {
        let rearr = [];
        for (let i = 0; i < this.DataV.area.length; i++) {
          let mode = [];
          for (let j = 0; j < arr.length; j++) {
            if (arr[j].area_id == this.DataV.area[i]) {
              mode.push(arr[j]);
            }
          }
          rearr.push(mode);
        }
        return rearr;
      },
      //判断是否开启导出按钮
      isShowExport(){
        if(this.showType == 'time'){
          for(let i in this.timeSize.list){
            if(this.timeSize.check == this.timeSize.list[i].tag){
              this.timeSize.isShow = this.timeSize.list[i].type == 'MIN' ? false : true
            }
          }
        }else{
          this.timeSize.isShow = true
        }
      }
    }
  };
</script>
